const OSS = require('ali-oss')
const COS = require('cos-nodejs-sdk-v5')
const qiniu = require('qiniu')
const ObsClient = require('esdk-obs-nodejs')
const { ApiError } = require('../utils/error')

class StorageService {
  /**
   * 测试阿里云OSS连接
   */
  async testAliyunOSS(config) {
    try {
      const client = new OSS({
        region: config.region,
        accessKeyId: config.accessKey,
        accessKeySecret: config.secretKey,
        bucket: config.bucket
      })
      
      // 列出文件测试连接
      await client.list({ 
        'max-keys': 1 
      })
      
      return true
    } catch (error) {
      throw new ApiError(400, '阿里云存储连接失败')
    }
  }

  /**
   * 测试腾讯云COS连接
   */
  async testTencentCOS(config) {
    try {
      const cos = new COS({
        SecretId: config.accessKey,
        SecretKey: config.secretKey
      })

      // 列出文件测试连接
      await new Promise((resolve, reject) => {
        cos.getBucket({
          Bucket: config.bucket,
          Region: config.region,
          MaxKeys: 1
        }, (err, data) => {
          if (err) {
            reject(err)
          } else {
            resolve(data)
          }
        })
      })

      return true
    } catch (error) {
      throw new ApiError(400, '腾讯云存储连接失败')
    }
  }

  /**
   * 测试七牛云存储连接
   */
  async testQiniuStorage(config) {
    try {
      const mac = new qiniu.auth.digest.Mac(config.accessKey, config.secretKey)
      const bucketManager = new qiniu.rs.BucketManager(mac)

      // 列出文件测试连接
      await new Promise((resolve, reject) => {
        bucketManager.listPrefix(config.bucket, {
          limit: 1
        }, (err, respBody, respInfo) => {
          if (err) {
            reject(err)
          } else if (respInfo.statusCode !== 200) {
            reject(new Error(respBody.error))
          } else {
            resolve(respBody)
          }
        })
      })

      return true
    } catch (error) {
      throw new ApiError(400, '七牛云存储连接失败')
    }
  }

  /**
   * 测试华为云OBS连接
   */
  async testHuaweiOBS(config) {
    try {
      const obsClient = new ObsClient({
        access_key_id: config.accessKey,
        secret_access_key: config.secretKey,
        server: `https://obs.${config.region}.myhuaweicloud.com`
      })

      // 列出文件测试连接
      await new Promise((resolve, reject) => {
        obsClient.listObjects({
          Bucket: config.bucket,
          MaxKeys: 1
        }, (err, result) => {
          if (err) {
            reject(err)
          } else if (result.CommonMsg.Status !== 200) {
            reject(new Error(result.CommonMsg.Message))
          } else {
            resolve(result)
          }
        })
      })

      return true
    } catch (error) {
      throw new ApiError(400, '华为云存储连接失败')
    }
  }

  /**
   * 测试存储连接
   */
  async testConnection(config) {
    if (config.type === 'local') {
      return true
    }

    switch (config.provider) {
      case 'aliyun':
        return await this.testAliyunOSS(config)
      case 'tencent':
        return await this.testTencentCOS(config)
      case 'qiniu':
        return await this.testQiniuStorage(config)
      case 'huawei':
        return await this.testHuaweiOBS(config)
      default:
        throw new ApiError(400, '不支持的服务商类型')
    }
  }
}

module.exports = new StorageService() 